<template>
  <view class="content" v-if="username">
    <!-- <view class="content-title">
      <view flex justify-between items-center m-20rpx>
        <div @click="back">
          <nut-icon name="left"></nut-icon>
        </div>
        <div>
          <text :style="{ width: textWidth + 'px' }">{{ username.name }}</text>
        </div>
        <div></div>
      </view>
    </view> -->
    <view class="content-body">
      <view class="message" :style="{ height: chatViewHeight + 'px' }">
        <scroll-view
          id="scrollId"
          :scroll-into-view="intoView"
          @scrolltoupper="scrollToUpper"
          :upper-threshold="50"
          :scroll-y="true"
          :scroll-top="scrollTop"
        >
          <div flex justify-center text-26rpx p-20rpx>
            {{ contentText[loadMore] }}
          </div>
          <view
            class="item"
            :id="'item_' + item.id"
            :key="item.id"
            v-for="(item, index) in chatList"
          >
            <chat-item
              :groupFlag="false"
              :showTime="showTime(index)"
              :username="username"
              :item="item"
            ></chat-item>
          </view>
        </scroll-view>
      </view>
      <view class="sender-content" >
        <view class="sender">
          <!--切换按钮-->
          <view>
            <!-- <image v-if="chatType === 'voice'" class="icon_img" src="/static/chat/voice.png"
                            @click="switchChatType('keyboard')"></image> -->
            <image
              v-if="chatType === 'keyboard'"
              class="icon_img"
              src="/pages/im/static/chat/keyboard.png"
              @click="switchChatType('voice')"
            ></image>
          </view>
          <!--文本框-->
          <view>
            <view class="textArea-box" v-if="chatType === 'voice'">
              <scroll-view :scroll-y="true" class="inputScroll">
                <textarea
                  placeholder-style="color:#DDDDDD;"
                  ref="textRef"
                  :auto-height="true"
                  :auto-focus="false"
                  :cursor-spacing="10"
                  @linechange="updateHeight"
                  :show-confirm-bar="false"
                  confirm-type="next"
                  :auto-blur="true"
                  :confirm-hold="true"
                  @focus="closeEmojiBox"
                  @keydown.enter="sendText"
                  v-model="sendStr"
                  :maxlength="1000"
                />
              </scroll-view>
            </view>
            <view class="voice_title" v-if="chatType === 'keyboard'">
              <!-- <voice-btn></voice-btn> -->
            </view>
          </view>
          <!--功能区-->
          <view>
            <image src="/pages/im/static/chat/emoji.png" @click="changeEmojiBox"></image>
            <!-- <image src="/static/chat/add.png"
                            :class="(chatType === 'keyboard' || sendStr.length === 0) ? '' : 'hidden'"
                            @click="changeFun"></image> -->
            <view class="send">
              <button type="primary" size="mini" @click="sendText">
                <text>发送</text>
              </button>
            </view>
          </view>
        </view>
        <!--表情-->
        <view class="fun-box" :class="{ 'show-fun-box': showEmojiBox }">
          <emoji v-show="showEmojiBox" @addEmoji="addEmoji"></emoji>
        </view>
        <!--功能-->
        <view class="fun-box" :class="{ 'show-fun-box': showFunBtn }">
          <fun-btn v-show="showFunBtn"></fun-btn>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import { onMounted, ref, onUnmounted } from 'vue'
import emoji from '@/pages/im/components/chat/components/emoji.vue'
import funBtn from '@/pages/im/components/chat/components/funbtn.vue'
import voiceBtn from '@/pages/im/components/chat/components/voiceBtn.vue'
import {
  sendChatMessage,
  start,
  stop
} from '@/pages/im/components/chat/utils/utils'
import { getTalkByUser, getTalkMessage } from '@/api/im'
import storage from '@/utils/storage'
import { useIMChatStore } from '@/pages/im/components/chat/utils'
import chatItem from './chatItem.vue'
import { storeToRefs } from 'pinia'
const store = useIMChatStore()
const { chatList } = storeToRefs(store)

const currentUser = storage.getUserInfo()

const chatf = ref<any>(null)
const username = ref<any>()
const chatViewHeight = ref(900)
const sendStr = ref('')
const chatType = ref('voice')
const showFunBtn = ref(false)
const showEmojiBox = ref(false)
const titleName = ref('')
const groupUserSize = ref(0)
const menuHeight = ref(20)
const menuTop = ref(20)
const intoView = ref('')
const scrollTop = ref<number>(0)
const loadMore = ref<string>('more')
const contentText = ref<any>({
  more: '下拉加载历史消息',
  loading: '正在加载...',
  noMore: ''
})
const param = reactive({
  talkId: 0,
  pageSize: 10,
  pageNumber: 1
})

const textWidth = ref(200)
const backType = ref('back')
onLoad(async (option) => {
  //获取当前网络状态
  uni.getNetworkType({
    success: function (res) {
      start()
    }
  })

  //监听网络变化
  uni.onNetworkStatusChange(function (res) {
    console.log('网络类型:' + res.networkType + ',网络连接:' + res.isConnected)
    if (!res.isConnected) {
      uni.showToast({
        title: '您的网络已断开连接！',
        icon: 'none'
      })
      stop()
      return
    } else {
      start()
    }
  })

  uni.onSocketOpen((res) => {
    console.log('WebSocket连接已打开！')
  })

  uni.onSocketError((res) => {
    console.log('WebSocket连接打开失败，请检查！')
  })

  uni.onSocketClose((res) => {
    console.log('WebSocket 已关闭！')
  })

  uni.onSocketMessage((res) => {
    console.log('收到服务器内容：' + res.data)
    const data = JSON.parse(res.data)

    setTimeout(() => {
      intoView.value = 'item_' + data.result.id
    }, 100)
    store.addItems(data.result)
  })

  if (option && option.userId) {
    console.log(option.userId)
    await getTalk(option.userId)
    //扫码进来的
    //   const scene = decodeURIComponent(option.scene);
    //   const user = await queryUser(scene)
    //   if (store.store.id === parseInt(scene)) {
    //     uni.showToast({
    //       title: '不能与自己聊天！',
    //       icon: 'error',
    //       duration: 2000
    //     });
    //     uni.switchTab({
    //       url: '/pages/friendList/friendList'
    //     });
    //     return
    //   }
    //   username.value = user!.username
    //   titleName.value = `${user!.nickName}`
  } else {
    await getTalk('1376433565247471616')
  }
  updateHeight()

  //1.计算标题长度
  // #ifdef MP-WEIXIN
  // const menu = uni.getMenuButtonBoundingClientRect()
  // menuTop.value = menu.top
  // menuHeight.value = menu.height + uni.upx2px(10); // 高度偏高一点
  // menuWidth.value = menu.left - uni.upx2px(10);
  // textWidth.value = menuWidth.value - uni.upx2px(130)
  // #endif
  //2.计算页面返回
  if (getCurrentPages().length === 1) {
    backType.value = 'home'
  }
})

onUnload(() => {
  stop()
})

onUnmounted(() => {
  stop()
  chatList.value = []
})

//是否展示时间
const showTime = (index: number): boolean => {
  if (index === 0) {
    return true
  }
  if (index === chatList.value.length - 1) {
    return true
  }
  if (index > 0) {
    const time =
      chatList.value[index].createTime! - chatList.value[index - 1].createTime!
    if (time > 60) {
      return true
    }
  }
  return false
}

//触底顶加载历史消息
const scrollToUpper = async () => {
  if (loadMore.value === 'more') {
    loadMore.value = 'loading'
    param.pageNumber++
    //加载消息
    const resp = await getTalkMessage(param)
    console.log('触底加载历史消息', resp)
    if (resp.data.result.length > 0) {
      chatList.value.unshift(...resp.data.result)
      //设置最新时间
      // param.time = resp.data.result[0].createTime + ''
      //设置滚动条位置
      intoView.value =
        'item_' + resp.data.result[resp.data.result.length - 1].id
      //设置状态
      if (resp.data.result.length < 10) {
        loadMore.value = 'noMore'
      } else {
        loadMore.value = 'more'
      }
    } else {
      loadMore.value = 'noMore'
    }
  }
}

const getTalk = async (talkId: string) => {
  const res = await getTalkByUser(talkId)
  //加载消息
  if (res.data.success) {
    username.value = res.data.result
    param.talkId = res.data.result.id
    if (res.data.result) {
      const resp = await getTalkMessage(param)
      if (resp.data.result.length > 0) {
        //设置最新时间
        setTimeout(() => {
          scrollTop.value = 9999
        }, 300)
        store.chatList = resp.data.result
        intoView.value =
          'item_' + resp.data.result[resp.data.result.length - 1].id
      }
      if (resp.data.result.length < 10) {
        loadMore.value = 'noMore'
      }
    }
  }
}

const back = () => {
  const pages = getCurrentPages()
  if (pages.length === 1) {
    uni.switchTab({
      url: '/pages/tabbar/mine'
    })
  } else {
    uni.navigateBack({
      delta: 1
    })
  }
}
const toChatInfo = () => {
  uni.navigateTo({
    url: `/pagesChat/chatView/chatInfo?username=${username.value}`
  })
}

const addEmoji = (em: any) => {
  sendStr.value += em.alt
}

//发送消息
const sendText = () => {
  if (sendStr.value.length === 0) {
    return
  }
  let objectDate = new Date()

  sendChatMessage(
    {
      userId: username.value.userId,
      fromId: currentUser.id,
      talkId: username.value.id,
      message: sendStr.value
    },
    () => {
      let time = objectDate.getTime()
      store.addItems({
        id: time,
        fromUser: currentUser.id,
        toUser: username.value.id,
        text: sendStr.value,
        createTime:
          objectDate.getFullYear() +
          '-' +
          (objectDate.getMonth() + 1) +
          '-' +
          objectDate.getDate() +
          ' ' +
          objectDate.getHours() +
          ':' +
          objectDate.getMinutes() +
          ':' +
          objectDate.getSeconds()
      })
      sendStr.value = ''
      setTimeout(() => {
        intoView.value = 'item_' + time
      }, 100)
    }
  )
}

//切换功能性按钮
const changeFun = () => {
  showEmojiBox.value = false
  showFunBtn.value = !showFunBtn.value
  uni.hideKeyboard()
  updateHeight()
}
//表情弹窗
const changeEmojiBox = () => {
  showFunBtn.value = false
  showEmojiBox.value = !showEmojiBox.value
  uni.hideKeyboard()
  if (showEmojiBox.value) {
    chatType.value = 'voice'
  }
  updateHeight()
}

const closeEmojiBox = () => {
  showEmojiBox.value = false
  updateHeight()
}

//切换语音或者键盘方式
const switchChatType = (type: string) => {
  chatType.value = type
  //底部菜单隐藏
  showFunBtn.value = false
  //底部菜单隐藏
  showFunBtn.value = false
  //表情弹窗
  if (showEmojiBox.value == true) {
    showEmojiBox.value = false
    updateHeight()
  }
  updateHeight()
}

const updateHeight = (flag?: boolean) => {
  const titleHeight = menuTop.value + menuHeight.value // 导航栏高度
  const windowHeight = uni.getSystemInfoSync().windowHeight

  // 获取iOS底部安全区高度
  const systemInfo:any = uni.getSystemInfoSync()
  console.log('systemInfo', systemInfo)
  const safeAreaBottom = systemInfo.safeAreaInsets.bottom || 0

  // 自动设置高度
  if (chatType.value === 'keyboard' && !showFunBtn.value) {
    chatViewHeight.value = windowHeight - uni.upx2px(122)
  } else {
    uni
      .createSelectorQuery()
      .select('.sender')
      .boundingClientRect((header) => {
        let height = header ? header.height : 0!
        /*if(height>=uni.upx2px(121)&&sendStr.value.length<=30){
              height=uni.upx2px(121)
            }*/
        if (showEmojiBox.value || showFunBtn.value) {
          height += uni.upx2px(320)
        }
        chatViewHeight.value = windowHeight - height - safeAreaBottom
        if (!flag) {
          setTimeout(() => {
            updateHeight(true)
          }, 50)
        }
      })
      .exec()
  }
}
</script>

<style lang="scss" scoped>
@import '@/pages/im/components/chat/components/chatview.scss';

fun-btn {
  width: 100vw;
}
</style>
